package zcjq.d912;

import beans.TreeNode;

import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

public class P2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String pre = "1 3 5 7 2";
        String mid = "5 3 1 2 7";

        List<Integer> preList = Arrays.stream(pre.split("\\s+")).map(Integer::parseInt).collect(Collectors.toList());
        List<Integer> midList = Arrays.stream(mid.split("\\s+")).map(Integer::parseInt).collect(Collectors.toList());
        int maxNode = preList.subList(1, preList.size()).stream().mapToInt(Integer::valueOf).max().getAsInt();
        TreeNode tree = TreeNode.parseToTreeFromPreAndMid(preList, midList);
        int[] max = new int[]{maxNode, 0};
        if (isSymmetric(tree.left, tree.right, max)) {
            System.out.println(max[1]);
        } else {
            System.out.println(maxNode);
        }
    }


    public static boolean isSymmetric(TreeNode leftNode, TreeNode rightNode, int[] max) {
        if (leftNode != null && rightNode == null) {
            return false;
        } else if (leftNode == null && rightNode != null) {
            return false;
        } else if (leftNode == null && rightNode == null) {
            return true;
        }
        if (leftNode.val == max[0]) {
            max[1] = rightNode.val;
        } else if (rightNode.val == max[0]) {
            max[1] = leftNode.val;
        }
        return isSymmetric(leftNode.left, rightNode.right, max) & isSymmetric(leftNode.right, rightNode.left, max);
    }
}
